package com.tankgame.utils;

import com.tankgame.models.BaseTank;

import java.awt.Rectangle;
import java.util.Vector;

// 使用单例模式实现坦克的防重叠
public class CollisionManager {
    private static CollisionManager instance;
    private Vector<BaseTank> allTanks = new Vector<>();
    private CollisionManager() {
        // 禁止实例化单例模式类
    }
    public static CollisionManager getInstance() {
        if (instance == null) {
            synchronized (CollisionManager.class) {
                if (instance == null) {
                    instance = new CollisionManager();
                }
            }
        }
        return instance;
    }
    public void addTank(BaseTank tank) {
        allTanks.add(tank);
    }

    public boolean canMove(BaseTank movingTank, int newX, int newY) {
        final int MARGIN = Math.max(Constants.TANK_HEIGHT , Constants.TANK_WIDTH ) / 2;

        for (BaseTank tank : allTanks) {
            if (tank.getId() == movingTank.getId()) continue;
            Rectangle newRect = new Rectangle(newX - Constants.TANK_WIDTH / 2,
                                             newY - Constants.TANK_HEIGHT / 2,
                                             Constants.TANK_WIDTH, Constants.TANK_HEIGHT);
            Rectangle existRect = new Rectangle(tank.getX() - Constants.TANK_WIDTH / 2,
                                               tank.getY() - Constants.TANK_HEIGHT / 2,
                                               Constants.TANK_WIDTH, Constants.TANK_HEIGHT);
            if (newRect.intersects(existRect)) {
                return false;
            }
        }
        return true;
    }

}